package info.techgeek.labs.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * This is a factory class which will give instance of the DAOClasses .
 * 
 * @author techgeek
 * 
 */
public class TableAccessManager {
	
	private static TableAccessManager tableAccessManager;
	private static HashMap<String, String> tableAccessManagerMap;

	String SDF_DATA_TYPE_DATE_FORMAT_DT_TI = "yyyy-MM-dd HH:mm:ss";
	private String dateFormat = SDF_DATA_TYPE_DATE_FORMAT_DT_TI;
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
	
	private TableAccessManager() {

	}

	public static TableAccessManager getInstance() {
		if (tableAccessManager == null) {
			tableAccessManager = new TableAccessManager();
		}
		getTableAccessManagerMap();
		return tableAccessManager;
	}

	private static HashMap<String, String> getTableAccessManagerMap() {
		if (tableAccessManagerMap == null) {
			tableAccessManagerMap = new HashMap<String, String>();
		}
		return tableAccessManagerMap;
	}
	
	private void insertTableLock(String tableName,String userCode,String time){
		
//		String time = simpleDateFormat.format(new Date());
		
//		String value = userCode+SqlViewerConstants.STRING_SEPARATOR_SEMICOLON+time;
		
		String value = getLockStatusMapValue(userCode, time);
		tableAccessManagerMap.put(tableName, value);
		
	}
	
	private String getLockStatusMapValue(String userCode,String time){
		String value = userCode+";"+time;
		return value;
	}
	
	private void removeTableLock(String tableName){
		getTableAccessManagerMap().remove(tableName);
	}
	
	private void updateTableLockStatus(String tableName,String userCode){
		String time = simpleDateFormat.format(new Date());
		
		if(tableAccessManagerMap.get(tableName) == null){
			insertTableLock(tableName, userCode, time);
		}else{
			String tableStatusValue = tableAccessManagerMap.get(tableName) ; 
			if(tableStatusValue.contains(userCode)){
				insertTableLock(tableName, userCode, time);
			}
			
		}
	}
	
	private  boolean checkStatusValidity(String tableStatusValue){
		
		boolean isValid = true;
		long tableLockLimit = 5;
		
		try {
			String tableLockStatusTime = tableStatusValue.split(";")[1];
		
			Date tableLockDate = simpleDateFormat.parse(tableLockStatusTime);
			long tableLockMilliSec = tableLockDate.getTime();
			
			Date currentDate = new Date();
			long currentMilliSec = currentDate.getTime();
			
			long difference = currentMilliSec - tableLockMilliSec;
			long minutes = (difference / (1000 * 60));
			
			if(minutes > tableLockLimit ){
				return false;
			}else{
				return isValid;
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return isValid;
	}
	
	public static void main(String[] args) {
		
		TableAccessManager accessManager = new TableAccessManager();
		boolean value = accessManager.checkStatusValidity("techgeek;2009-08-28 11:25:00");
		System.out.println("value "+value);
	}
}
